package com.ochnas.examples.jsf.service;

import java.util.*;

import com.ochnas.examples.jsf.domain.Bike;

public class ArrayListRentABike implements RentABike {

    private String storeName;
    final List bikes = new ArrayList(  );

    public ArrayListRentABike() {
		super();
		initBikes();
	}
    
    public void initBikes() {
    	bikes.add(new Bike("Shimano", "Roadmaster", 20, "11111", 15,
        "Fair"));
    	bikes.add(new Bike("Cannondale", "F2000 XTR", 18, "22222",12,
        "Excellent"));
    	bikes.add(new Bike("Trek","6000", 19, "33333", 12.4,
        "Fair"));
    }

	public ArrayListRentABike(String storeName) {
        this.storeName = storeName;
        initBikes();
    }

    public String toString(  ) { return "RentABike: " + storeName; }

    public List getBikes(  ) { return bikes; }
    public void setBikes(List bikes) {
    	this.bikes.clear();
    	this.bikes.addAll(bikes);
    }

    public Bike getBike(String serialNo) {
        Iterator iter = bikes.iterator(  );
        while(iter.hasNext(  )) {
            Bike bike = (Bike)iter.next(  );
            if(serialNo.equals(bike.getSerialNo(  ))) return bike;
        }
        return null;
    }

	public String getStoreName() {
		return storeName;
	}

	public void setStoreName(String storeName) {
		this.storeName = storeName;
	}

	@Override
	public void deletBike(Bike bike) {
		deleteIfContains(bike);
	}

	@Override
	public void saveBike(Bike bike) {
		deleteIfContains(bike);
		bikes.add(bike);		
	}
	
	private void deleteIfContains(Bike bike) {
		
		Iterator iter = bikes.iterator();
		while(iter.hasNext()) {
			Bike comp = (Bike)iter.next();
			if(comp.getManufacturer().equals(bike.getManufacturer()) &&
					comp.getModel().equals(bike.getModel())) {
				bikes.remove(comp);
				return;
			}
		}
	}
}